package com.fjrz.bbxwj.mode.vm

import android.app.Application
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.ToastUtils
import com.fjrz.bbxwj.entity.*
import com.module.lemlin.base.BaseViewModel
import com.module.lemlin.mode.ViewModelSubscribe
import com.module.lemlin.rxhttp.HttpServiceData
import com.module.lemlin.rxhttp.HttpServiceResponse
import com.fjrz.bbxwj.entity.*
import com.fjrz.bbxwj.mode.api.*
import com.fjrz.bbxwj.mode.manager.UploadProgress
import com.fjrz.bbxwj.mode.manager.commonUpload
import com.fjrz.bbxwj.popup.VideoDiscussPopup
import com.module.lemlin.rxhttp.code
import com.module.lemlin.rxhttp.msg
import io.reactivex.rxjava3.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import rxhttp.wrapper.entity.Progress
import java.io.BufferedInputStream
import java.io.File
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLConnection

class VideoViewModel(application: Application) : BaseViewModel(application) {


    val uploadLiveData = MutableLiveData<HttpServiceResponse<UploadResponse>>()
    val progressLiveData = MutableLiveData<Progress>()

    /**
     * 上传视频
     * */
    fun commonUpload(path: String, type: UploadResponse.Type = UploadResponse.Type.FILE_NULL) {
        if (path.isNullOrEmpty())
            return
        val progress = object : UploadProgress {
            override fun onProgress(progress: Progress) {
                progressLiveData.postValue(progress)
            }
        }
        val listener = object : ViewModelSubscribe<UploadResponse>(uploadLiveData) {
            override fun onSuccess(resp: UploadResponse) {
                super.onSuccess(resp.apply { this.type = type })
            }
        }
        val disposable: Disposable =
            commonUpload(File(path), progress, listener)
        dispose.add(disposable)
    }


    private var page: Int = 1
    private var limit: Int = 10


    val videoListLiveData = MutableLiveData<HttpServiceResponse<VideoListResponse>>()

    /**
     * 视频列表数据
     *
     * @param cateId 分类ID: -2朋友 -1推荐
     * */
    fun videoIndex(cateId: Int = -2, isLoadMore: Boolean = false) {
        val listener = object : ViewModelSubscribe<VideoListResponse>(videoListLiveData) {
            override fun onSuccess(resp: VideoListResponse) {
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (!isLoadMore)
            page = 1
        val disposable: Disposable =
            videoIndex(limit.toString(), cateId.toString(), listener)
        dispose.add(disposable)
    }

    val videoCateDefaultListLiveData = MutableLiveData<HttpServiceResponse<VideoCateListResponse>>()

    /**
     * 默认分类列表（顶上的分类列表）
     * */
    fun videoDefaultCateList() {
        val disposable: Disposable =
            videoDefaultCateList(ViewModelSubscribe(videoCateDefaultListLiveData))
        dispose.add(disposable)
    }

    val videoCateTotalListLiveData = MutableLiveData<HttpServiceResponse<VideoCateListResponse>>()

    /**
     * 所有分类列表
     * */
    fun videoCateTotalList() {
        val disposable: Disposable =
            videoCateList(ViewModelSubscribe(videoCateTotalListLiveData))
        dispose.add(disposable)
    }

    val videoSetCateLiveData = MutableLiveData<HttpServiceResponse<VideoCateSetResponse>>()

    /**
     * 设置分类
     *
     * @param cateIds 选中的分类（逗号隔开，推荐和朋友不加入）
     * */
    fun videoSetCate(cateIds: String, videoCateList: VideoCateList, type: Int) {
        val listener = object : ViewModelSubscribe<VideoCateSetResponse>(videoSetCateLiveData) {
            override fun onSuccess(resp: VideoCateSetResponse) {
                super.onSuccess(resp.apply {
                    this.videoCateList = videoCateList
                    this.type = type
                })
            }
        }
        val disposable: Disposable = videoSetCate(cateIds, listener)
        dispose.add(disposable)
    }


    val videoAddOrEditLiveData = MutableLiveData<HttpServiceResponse<HttpServiceData>>()

    /**
     * 添加视频
     * */
    fun videoAdd(request: VideoRequest) {
        val disposable: Disposable =
            videoAdd(request.apply {
                action = null
                path_advert = null
                path_bitmap = null
                path_video = null
            }, ViewModelSubscribe(videoAddOrEditLiveData))
        dispose.add(disposable)
    }

    fun videoEdit(request: VideoRequest) {
        val disposable: Disposable =
            videoEdit(request.apply {
                action = null
                path_advert = null
                path_bitmap = null
                path_video = null
            }, ViewModelSubscribe(videoAddOrEditLiveData))
        dispose.add(disposable)
    }

    val videoDetailsLiveData = MutableLiveData<HttpServiceResponse<VideoDetailsResponse>>()

    /**
     * 视频详情
     *
     * @param videoId 视频id,多个用逗号隔开
     * */
    fun videoDetail(videoId: Int) {
        val disposable: Disposable =
            videoDetail(videoId.toString(), ViewModelSubscribe(videoDetailsLiveData))
        dispose.add(disposable)
    }


    /**
     * 关注
     *
     * @param userId
     * */
    fun userFollow(userId: Int) {
        val listener = object : ViewModelSubscribe<HttpServiceData>(MutableLiveData()) {
            override fun onSuccess(resp: HttpServiceData) {
                super.onSuccess(resp)
                EventBus.getDefault().post(UserIsFollow(user_id = userId, isFollow = 1))
            }

            override fun onFailure(throwable: Throwable) {
                super.onFailure(throwable)
                if (throwable.code != 401) {
                    ToastUtils.showShort(throwable.msg)
                }
            }
        }
        val disposable: Disposable = userFollow(userId.toString(), listener)
        dispose.add(disposable)
    }

    /**
     * 视频点赞
     *
     * @param videoId 视频id
     * */
    fun videoLike(videoId: Int) {
        val listener = object : ViewModelSubscribe<VideoLikeResponse>(MutableLiveData()) {
            override fun onSuccess(resp: VideoLikeResponse) {
                super.onSuccess(resp)
                val videoIsLike = VideoIsLike(
                    video_id = videoId, like_count = resp.data.like_count, isLike = 1
                )
                EventBus.getDefault().post(videoIsLike)
            }

            override fun onFailure(throwable: Throwable) {
                super.onFailure(throwable)
                if (throwable.code != 401) {
                    ToastUtils.showShort(throwable.msg)
                }
            }
        }
        val disposable: Disposable = videoLike(videoId.toString(), listener)
        dispose.add(disposable)
    }

    /**
     * 取消点赞
     *
     * @param videoId 视频id
     * */
    fun videoUnLike(videoId: Int) {
        val listener = object : ViewModelSubscribe<VideoLikeResponse>(MutableLiveData()) {
            override fun onSuccess(resp: VideoLikeResponse) {
                super.onSuccess(resp)
                val videoIsLike = VideoIsLike(
                    video_id = videoId, like_count = resp.data.like_count, isLike = 0
                )
                EventBus.getDefault().post(videoIsLike)
            }

            override fun onFailure(throwable: Throwable) {
                super.onFailure(throwable)
                if (throwable.code != 401) {
                    ToastUtils.showShort(throwable.msg)
                }
            }
        }
        val disposable: Disposable = videoUnLike(videoId.toString(), listener)
        dispose.add(disposable)
    }


    /**
     * 视频同城
     *
     * @param city 同城
     * */
    fun videoSameCityList(city: String, isLoadMore: Boolean = false) {
        val listener = object : ViewModelSubscribe<VideoListResponse>(videoListLiveData) {
            override fun onSuccess(resp: VideoListResponse) {
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (!isLoadMore)
            page = 1
        val disposable: Disposable =
            videoSameCityList(city, page.toString(), limit.toString(), listener)
        dispose.add(disposable)
    }

    val commentGroupLiveData = MutableLiveData<HttpServiceResponse<CommentGroupResponse>>()

    /**
     * 评论列表
     *
     * @param videoId 视频id
     * */
    fun commentList(videoId: Int, isLoadMore: Boolean = false) {
        val listener = object : ViewModelSubscribe<CommentGroupResponse>(commentGroupLiveData) {
            override fun onSuccess(resp: CommentGroupResponse) {
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (!isLoadMore)
            page = 1
        val disposable: Disposable = commentList(
            videoId.toString(), page.toString(), limit.toString(), listener
        )
        dispose.add(disposable)
    }


    val commentChildLiveData = MutableLiveData<HttpServiceResponse<CommentChildResponse>>()

    /**
     * 子评论列表
     *
     * @param baseCommentId
     * */
    fun commentChildList(baseCommentId: Int, position: Int) {
        val listener = object : ViewModelSubscribe<CommentChildResponse>(commentChildLiveData) {
            override fun onSuccess(resp: CommentChildResponse) {
                super.onSuccess(resp.apply { this.position = position })
            }
        }
        val disposable: Disposable = commentChildList(
            baseCommentId.toString(), listener
        )
        dispose.add(disposable)
    }


    val commentGreatLiveData = MutableLiveData<HttpServiceResponse<CommentGreatResponse>>()

    /**
     * 评论点赞
     *
     * @param commentId
     * */
    fun commentLike(commentId: Int, position: Int) {
        val listener = object : ViewModelSubscribe<CommentGreatResponse>(commentGreatLiveData) {
            override fun onSuccess(resp: CommentGreatResponse) {
                super.onSuccess(resp.apply {
                    this.isList = 1
                    this.position = position
                })
            }
        }
        val disposable: Disposable = commentLike(
            commentId.toString(), listener
        )
        dispose.add(disposable)
    }

    /**
     * 取消评论点赞
     *
     * @param commentId
     * */
    fun commentUnLike(commentId: Int, position: Int) {
        val listener = object : ViewModelSubscribe<CommentGreatResponse>(commentGreatLiveData) {
            override fun onSuccess(resp: CommentGreatResponse) {
                super.onSuccess(resp.apply {
                    this.isList = 0
                    this.position = position
                })
            }
        }
        val disposable: Disposable = commentUnLike(
            commentId.toString(), listener
        )
        dispose.add(disposable)
    }


    val commentSubmitLiveData = MutableLiveData<HttpServiceResponse<CommentSubmitResponse>>()

    /**
     * 视频评论
     *
     * @param content
     * */
    fun commentSubmit(content: VideoDiscussPopup.Content) {
        val listener = object : ViewModelSubscribe<CommentSubmitResponse>(commentSubmitLiveData) {
            override fun onSuccess(resp: CommentSubmitResponse) {
                super.onSuccess(resp)
                content.video_id?.let {
                    commentList(it.toInt())
                }
            }
        }
        val disposable: Disposable = commentSubmit(content, listener)
        dispose.add(disposable)
    }

    val userShieldLiveData = MutableLiveData<HttpServiceResponse<HttpServiceData>>()

    /**
     * 屏蔽视频 / 用户
     *
     * @param type 类型：1=屏蔽视频 2=屏蔽用户
     * @param targetId 视频ID / 用户ID
     * */
    fun userShield(type: Int, targetId: Int) {
        val disposable: Disposable =
            userShield(
                type.toString(), targetId.toString(),
                ViewModelSubscribe(userShieldLiveData)
            )
        dispose.add(disposable)
    }


    val videoAdvertisingSignUpLiveData = MutableLiveData<HttpServiceResponse<HttpServiceData>>()

    /**
     * 广告报名
     *
     * @param mobile
     * @param videoId 视频id
     * */
    fun videoAdvertisingSignUp(mobile: String, videoId: Int) {
        val disposable: Disposable =
            videoAdvertisingSignUp(
                mobile, videoId.toString(),
                ViewModelSubscribe(videoAdvertisingSignUpLiveData)
            )
        dispose.add(disposable)
    }


    val videoShareLiveData = MutableLiveData<HttpServiceResponse<VideoShareResponse>>()

    /**
     * */
    fun videoShare(type: String, id: String) {
        val disposable: Disposable =
            commentShare(
                type, id,
                ViewModelSubscribe(videoShareLiveData)
            )
        dispose.add(disposable)
    }




}